import XLSX, {
  WorkSheet
} from "xlsx";

export default {
  // 向此函数传入从后端返回来的统计数据，会返回一个posts数组，它的结构是这样的
  // [
  //  {id:1,questiontitle:'请选yes或no',totalquantity:4,allanswers:[],answers:[{option:'A',text:'yes',quantity:2},{option:'B',text:'no',quantity:2}]
  //  {id:2,questiontitle:'请选yes或no',totalquantity:4,answers:[{option:'A',text:'yes',quantity:2},{option:'B',text:'no',quantity:2}]
  // ]
  // 直接将这个返回的结果当作posts传入StaticCard即可
  getStaticPosts(res) {
    var a = [];
    var source = res.data.statistical_feature;
    for (let item of Object.keys(source)) {
      var b = {
        id: item,
        questiontitle: "",
        totalquantity: 10,
        answers: []
      };
      var r = res.data.statistical_feature[item]; //获取的数据的每一题
      var c = r.choose_distribution; //c是选项的对象
      var sum = 0; //储存被选总次数
      // 循环选项
      for (let iitem of Object.keys(c)) {
        var aa = {
          option: "",
          text: "",
          quantity: 0
        }; //每一个选项的模板
        aa.option = iitem.replace(/_/g, ""); //每一个选项的标题，比如'A','B'
        aa.quantity = c[iitem]; //每一个选项的被选次数
        sum += aa.quantity;
        b.answers.push(aa); //把每一个选项push到b的answer对象里面
      }
      b.totalquantity = sum; //获取选项被选的总次数
      a.push(b); //把每一题都push到a对象里面
    }
    return a;
  },
  itemTypeTransformer(qtype) {
    switch (qtype) {
      case "single":
        return "qitem-radio";
      case "multi":
        return "qitem-checkbox";
      case "blank":
        return "qitem-text-blank";
      case "rate":
        return "qitem-rate";
      case "location":
        return "qitem-location";
    }
  },
  editorTypeTransformer(qtype) {
    switch (qtype) {
      case "single":
        return "qeditor-radio";
      case "multi":
        return "qeditor-checkbox";
      case "blank":
        return "qeditor-text-blank";
      case "rate":
        return "qeditor-rate";
      case "location":
        return "qeditor-location";
    }
  },
  initOptions(type) {
    // 根据问卷类型选择题目类型
    let options = {};
    switch (type) {
      case "normal":
        options = {
          autoJudge: false,
          showResult: false,
          limitNumber: false
        };
        break;
      case "vote": {
        options = {
          autoJudge: false,
          showResult: true,
          limitNumber: false
        };
        break;
      }
      case "sign": {
        options = {
          autoJudge: false,
          showResult: false,
          limitNumber: true
        };
        break;
      }
      case "exam": {
        options = {
          autoJudge: true,
          showResult: false,
          limitNumber: false
        };
        break;
      }
      default: {
        options = {
          autoJudge: false,
          showResult: false,
          limitNumber: false
        };
      }
    }
    return options;
  },
  _newOption(label) {
    return {
      label,
      isAnswer: false,
      limited: false,
      amount: 10
    }
  },
  ipToKey(IP) {
    // 将IP映射到一个值，用于乱序
    if (IP == undefined)
      IP = '123.456.789'
    var key = 0;
    for (var i = 0, len = IP.length; i < len; i++) {
      let ch = IP[i]
      let num = 10
      if (ch <= '9' && ch >= '0')
        num = ch - '0'
      key = key * 3 + num
    }
    return key.toString().split("")
  },
  initVote() {
    let single = this.creatNewQuestion("single");
    single.title = '投票题'
    single.description = '请在此投票'
    return [single]
  },
  initSign() {
    let name = this.creatNewQuestion("blank");
    let phone = this.creatNewQuestion("blank");
    let sign = this.creatNewQuestion("single");
    name.title = '姓名'
    name.description = "您的姓名为___";
    name.title = '手机号码'
    phone.description = "您的手机号码为___";
    sign.title = '报名项'
    sign.description = '请选择报名'
    return [name, phone, sign]
  },
  initLocation() {
    // 姓名
    let name = this.creatNewQuestion("blank");
    name.title = '姓名'
    name.description = "您的姓名为___";
    // 学号
    let sid = this.creatNewQuestion("blank");
    sid.title = '学号'
    sid.description = "您的学号为___";
    // 体温单选
    let temp = this.creatNewQuestion("single");
    temp.title = '体温'
    temp.description = "请选择您的体温";
    temp.options = [
      this._newOption('正常（37.2℃及以下）'),
      this._newOption('37.3℃-38℃'),
      this._newOption('38.1℃-38.5℃'),
      this._newOption('38.6℃-39℃'),
      this._newOption('39.1℃-40℃'),
      this._newOption('40.1℃以上'),
    ];
    // 风险单选
    let riskArea = this.creatNewQuestion("single");
    riskArea.title = "最近14日是否去过中高风险地区？";
    riskArea.description = "";
    riskArea.options = [this._newOption('去过'), this._newOption('没去过')];
    // 新冠症状
    let symptom = this.creatNewQuestion("single");
    symptom.title = "有无新冠症状？";
    symptom.description = "";
    symptom.options = [this._newOption('有新冠症状'), this._newOption('无新冠症状')];
    // 定位
    let location = this.creatNewQuestion("location");
    location.title = '定位'
    location.description = "请允许问卷对您定位";
    return [name, sid, temp, riskArea, symptom, location]
  },
  initExam() {
    let name = this.creatNewQuestion("blank", 'exam');
    let sid = this.creatNewQuestion("blank", 'exam');
    name.description = "您的姓名为___";
    sid.description = "您的学号为___";
    return [name, sid]
  },
  creatNewQuestion(type, stype) {
    let chosen = [-1, -1]
    if (stype == 'exam')
      chosen = ['无']
    let obj = {
      type,
      description: "此处是题目描述",
      // label: qitem.label,
      masked: true,
      title: "新问题",
      must: true,
      min: 0,
      max: 5,
      options: [],
      chosen, //此处为了适配选择题不编辑情况
      key: 1,
      score: 0,
      order: -1,
      showResult: false
    };
    switch (type) {
      case 'blank':
        obj.description = "我是填空题,你的名字是___"
        obj.options = ["无"]
        break;
      case 'rate':
        obj.description = "我是评分题"
        break;
      case 'multi':
        obj.description = "我是多选题"
        obj.options.push(this._newOption("A"))
        obj.options.push(this._newOption("B"))
        break
      case 'single':
        obj.description = "我是单选题"
        obj.options.push(this._newOption("A"))
        obj.options.push(this._newOption("B"))
        break;
      case 'location':
        obj.description = "地理位置题"
        break;
    }
    return obj
  },
  exportAllAnswers(allAnswers, survey) { //导出所有答案，填写人，填写时间。直接传入从后端获取的答卷统计原始数据。
    var excelData = []
    var cAnswers = allAnswers.correct_answer //用于统计题目数量
    var titles = ["填写者", "填写时间"] // 标题
    let ques = survey.Questions
    cAnswers.forEach((element, index) => {
      let order = index + 1
      titles.push(order + "." + ques[index].title + ":" + ques[index].description)
    });
    excelData.push(titles)

    var answers = allAnswers.all_answers
    var keys = Object.keys(answers)
    keys.forEach(key => {
      let item = [] // 数据，与标题一一对应
      item.push(answers[key].UID) //填写人
      item.push(new Date(answers[key].timeStamp).toLocaleString()) //填写时间
      for (let answer of answers[key].answers) {
        // answer = [1,2,3]
        item.push(answer.toString())
      }
      excelData.push(item)
    })

    console.log('all answers', excelData)

    let worksheet = XLSX.utils.aoa_to_sheet(excelData)
    let workbook = XLSX.utils.book_new()
    XLSX.utils.book_append_sheet(workbook, worksheet, "第一页")
    XLSX.writeFile(workbook, "分析结果.xlsx")
  },
}